package com.takeaway.ui.activity

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import com.takeaway.R
import android.support.v4.app.Fragment
import android.util.Log
import android.widget.FrameLayout
import com.takeaway.ui.fragment.HomeFragment
import com.takeaway.ui.fragment.MineFragment
import com.takeaway.ui.fragment.OrderFragment
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {


    private val fragments = listOf<Fragment>(HomeFragment(), OrderFragment(), MineFragment())
    private var lastIndex = -1
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        changeTabBar()
        changeState(0)
    }

    private fun changeTabBar() {
        for (index in 0 until main_bottom_bar.childCount) {
            main_bottom_bar.getChildAt(index).setOnClickListener {
                changeState(index)
            }
        }
    }

    private fun changeState(index: Int) {
        Log.e("Mian", "index = " + index)
        for (i in 0 until main_bottom_bar.childCount) {
            Intent()
            val frameLayout = main_bottom_bar.getChildAt(i) as FrameLayout

            if (i == index) {
                frameLayout.isEnabled = false
                for (j in 0 until frameLayout.childCount) {
                    frameLayout.getChildAt(j).isEnabled = false
                }
            } else {
                frameLayout.isEnabled = true
                for (j in 0 until frameLayout.childCount) {
                    frameLayout.getChildAt(j).isEnabled = true
                }
            }
        }
        // 性能问题 导致fragment重新初始化
//        supportFragmentManager.beginTransaction().replace(R.id.main_content, fragments[index]).commit()
        val transaction = supportFragmentManager.beginTransaction()
        if (lastIndex >= 0) {
            val lastFragment = fragments[lastIndex]
            transaction.hide(lastFragment)
        }
        val currentFragment = fragments[index]
        if (currentFragment.isAdded) {
            transaction.show(currentFragment)
        } else {
            transaction.add(R.id.main_content, currentFragment)
        }
        transaction.commit()
        lastIndex = index

        // 底部状态栏的问题
    }
}
